const categoryService = require('../../services/good/categoryService');
const response = require('../../utils/response');
const { handleDatabaseError } = require('../../utils/dberrordeal');
class CategoryController {
    static async getCategoryList(ctx) {
        const { pageNum = 1, pageSize = 10 } = ctx.request.body;
        const data = ctx.request.body||{};
        delete data.pageNum;
        delete data.pageSize;
        const res = await categoryService.getCategoryList({ pageNum, pageSize }, data);
        res ? response.success(ctx, { data: res }) : response.error(ctx, {});
    }
    static async getCategoryById(ctx) {
        const { id: categoryId } = ctx.request.body;
        const res = await categoryService.getCategoryById(categoryId);
        res ? response.success(ctx, { data: res }) : response.error(ctx, { message: '分类不存在' });
    }
    static async createCategory(ctx) {
        const categoryData = ctx.request.body;
        if (!categoryData.parentId) {
            categoryData.parentId = '0'; // 根节点的 parentId 为 '0'
        }
        
        // 根据父分类设置当前分类的级别
        if (categoryData.parentId !== '0') {
            const parentCategory = await categoryService.getCategoryById(categoryData.parentId);
            if (!parentCategory) {
                return response.error(ctx, { message: '父分类不存在' });
            }
            categoryData.level = (parentCategory.level || 0) + 1;
            
            // 当添加子分类时，父分类不再是叶子节点
            await categoryService.updateCategory(categoryData.parentId, { leaf: false });
        } else {
            categoryData.level = 0; // 根分类级别为0
        }

        // 检查相同ParentId分类名称是否已存在
        const existingCategories = await categoryService.getCategoryByParentId(categoryData.parentId);
        if (existingCategories.some(cat => cat.name === categoryData.name)) {
            return response.error(ctx, { message: '同一父分类下分类名称不能重复' });
        }

        await categoryService.createCategory(categoryData)
            .then(async (res) => {
                if (res && categoryData.parentId !== '0') {
                    const parentCategory = await categoryService.getCategoryById(categoryData.parentId);
                    if (!parentCategory) {
                        // 如果父分类不存在，回滚创建操作
                        await categoryService.deleteCategory(res._id);
                        return response.error(ctx, { message: '父分类不存在' });
                    }
                    const parentIds = parentCategory.parentIds || [];
                    await categoryService.updateCategory(
                        res._id,
                        {
                            parentIds: [...parentIds, parentCategory._id]
                        }
                    );
                }
                response.success(ctx, {})
            })
            .catch(err => handleDatabaseError(ctx, err, '分类名称重复'));
    }
    static async updateCategory(ctx) {
        const categoryData = ctx.request.body;
        if (!categoryData.parentId) {
            categoryData.parentId = '0'; // 根节点的 parentId 为 '0'
        }
        
        // 根据父分类设置当前分类的级别
        if (categoryData.parentId !== '0') {
            const parentCategory = await categoryService.getCategoryById(categoryData.parentId);
            if (!parentCategory) {
                return response.error(ctx, { message: '父分类不存在' });
            }
            categoryData.level = (parentCategory.level || 0) + 1;
            
            // 当添加子分类时，父分类不再是叶子节点
            await categoryService.updateCategory(categoryData.parentId, { leaf: false });
        } else {
            categoryData.level = 0; // 根分类级别为0
        }

        // 检查相同ParentId分类名称是否已存在
        const existingCategories = await categoryService.getCategoryByParentId(categoryData.parentId);
        if (existingCategories.some(cat => cat.name === categoryData.name && cat._id !== categoryData.id)) {
            return response.error(ctx, { message: '同一父分类下分类名称不能重复' });
        }
        await categoryService.updateCategory(categoryData.id, categoryData)
            .then(async (res) => {
                if (res) {
                    if (categoryData.parentId === '0') {
                        return response.success(ctx, {}); // 对于根分类，不更新 parentIds
                    }
                    const parentCategory = await categoryService.getCategoryById(categoryData.parentId);
                    if (!parentCategory) {
                        return response.error(ctx, { message: '父分类不存在' });
                    }
                    const parentIds = parentCategory.parentIds || [];

                    await categoryService.updateCategory(
                        res._id,
                        {
                            parentIds: [...parentIds, parentCategory._id]
                        }
                    );
                }
                response.success(ctx, {})

            })
            .catch(err => handleDatabaseError(ctx, err, '分类名称重复'));
    }

    static async deleteCategory(ctx) {
        const { id: categoryId } = ctx.request.body;
        //所有商品中存在parentId为categoryId的商品则不允许删除
        const existingCategory = await categoryService.getCategoryByParentId(categoryId);
        if (existingCategory.length > 0) {
            return response.error(ctx, { message: '该分类下存在子分类,请先修改子分类的父类或者删除此分类，否则无法删除' });
        }
        //查看此分类详情
        const cres = await categoryService.getCategoryById(categoryId);
        const res = await categoryService.deleteCategory(categoryId);
        
        // 如果被删除的分类有父分类，检查父分类是否还有其他子分类
        if (cres && cres.parentId && cres.parentId !== '0') {
            const fres = await categoryService.getCategoryById(cres.parentId);
            if (fres) {
                const existingSonCategory = await categoryService.getCategoryByParentId(fres._id);
                // 如果父分类没有其他子分类了，则将其标记为叶子节点
                if (existingSonCategory.length === 0) {
                    await categoryService.updateCategory(fres._id, { leaf: true });
                }
            }
        }
        res ? response.success(ctx, {}) : response.error(ctx, {});
    }
}
module.exports = CategoryController;